package com.neihanduanzi.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.neihanduanzi.BaseActivity;
import com.neihanduanzi.R;
import com.neihanduanzi.adapter.ImageAdapter;
import com.neihanduanzi.api.ImageService;
import com.neihanduanzi.database.DButil;
import com.neihanduanzi.database.ImageDb;
import com.neihanduanzi.model.ImageModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class ZImageFragment extends BaseFragment implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    private List<ImageModel.Data> mData;
//    private ImageListAdapter mAdapter;
    private View ret;
//    private RecyclerView imageList;
    private ImageService mImageService;
    private ImageModel.Data data;
    private ListView imageList;
    private ImageAdapter mAdapter;
    private SwipeRefreshLayout mRefreshLayout;


    public ZImageFragment() {

    }

    @Override
    public String getFragmentTitle() {
        return "图片";
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mData = new ArrayList<>();
//        mAdapter = new ImageListAdapter(getContext(), mData);
        mAdapter = new ImageAdapter(getContext(), mData);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ret = inflater.inflate(R.layout.fragment_zimage, container, false);

        imageList = (ListView)ret.findViewById(R.id.image_list);
        imageList.setAdapter(mAdapter);
        mRefreshLayout = (SwipeRefreshLayout)ret. findViewById(R.id.refresh);
        mRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.pink));
        mRefreshLayout.setOnRefreshListener(this);


        initDatabase();
        initData();

        imageList.setOnItemClickListener(this);
        return ret;
    }

    private void initDatabase() {
        List<ImageDb> imageDbs = DButil.queryAllImage();
        if (imageDbs != null) {
            String group = imageDbs.get(0).getGroup();
            load(group);
        }
    }

    private void initData() {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://ic.snssdk.com/neihan/");
        builder.addConverterFactory(ScalarsConverterFactory.create());
        Retrofit build = builder.build();
        mImageService = build.create(ImageService.class);
        Call<String> call = mImageService.getImageList();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response != null){
                    mRefreshLayout.setRefreshing(false);
                    String body = response.body();
                    load(body);
                    if (body != null) {
                        DButil.deleteImage();
                        ImageDb imageDb = new ImageDb();
                        imageDb.setGroup(body);
                        DButil.addData(imageDb);
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void load(String body) {
        try {
            mData.clear();
            JSONObject json = new JSONObject(body);
            JSONObject jsonData = json.getJSONObject("data");
            String message = json.optString("message");
            Log.d("message", "message = " + message);
            System.out.println("data = " + jsonData.toString());

            Gson gson = new Gson();
            ImageModel imageModel = gson.fromJson(jsonData.toString(), ImageModel.class);
            mData.addAll(imageModel.getData());
            mAdapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ImageModel.Data.Group group = mData.get(position).getGroup();
        Gson gson = new Gson();
        String str = gson.toJson(group);
        Intent intent = new Intent(getContext(), BaseActivity.class);
        intent.putExtra("Data", str);
        intent.putExtra("type",3);
        intent.putExtra("group_id",group.getGroup_id());
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        initData();
    }


}
